<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="《java并发编程的艺术》第五章总结, 戴某的博客">
    <meta name="description" content="戴某的笔记">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>《java并发编程的艺术》第五章总结 | 戴某的博客</title>
    <link rel="icon" type="image/png" href="/dai_modest/favicon.png">

    <link rel="stylesheet" type="text/css" href="/dai_modest/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/dai_modest/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/dai_modest/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/dai_modest/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/dai_modest/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/dai_modest/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/dai_modest/css/my.css">

    <script src="/dai_modest/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/dai_modest/atom.xml" title="戴某的博客" type="application/atom+xml">
<link rel="stylesheet" href="/dai_modest/css/prism-tomorrow.css" type="text/css"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/dai_modest/" class="waves-effect waves-light">
                    
                    <img src="/dai_modest/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">戴某的博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/dai_modest/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/dai_modest/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/dai_modest/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/dai_modest/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/dai_modest/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/dai_modest/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/dai_modest/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/dai_modest/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">戴某的博客</div>
        <div class="logo-desc">
            
            戴某的笔记
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/dai_modest/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/dai_modest/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/dai_modest/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/dai_modest/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/dai_modest/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/dai_modest/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/dai_modest/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/dai_modest/medias/featureimages/6.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">《java并发编程的艺术》第五章总结</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/dai_modest/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/dai_modest/tags/java/">
                                <span class="chip bg-color">java</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/dai_modest/categories/%E4%B9%A6%E7%B1%8D/" class="post-category">
                                书籍
                            </a>
                        
                            <a href="/dai_modest/categories/%E4%B9%A6%E7%B1%8D/%E7%AC%94%E8%AE%B0%E7%B1%BB/" class="post-category">
                                笔记类
                            </a>
                        
                            <a href="/dai_modest/categories/%E4%B9%A6%E7%B1%8D/%E7%AC%94%E8%AE%B0%E7%B1%BB/%E3%80%8Ajava%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E7%9A%84%E8%89%BA%E6%9C%AF%E3%80%8B/" class="post-category">
                                《java并发编程的艺术》
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-04-16
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-04-16
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    6.4k
                </div>
                

                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/dai_modest/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="Lock接口"><a href="#Lock接口" class="headerlink" title="Lock接口"></a>Lock接口</h1><p>锁的作用：锁是用来控制多个线程访问共享资源的方式，一个锁能够防止多个线程同时访问共享资源。</p>
<p>javaSE 5后，并发包中新增了Lock接口用来实现锁功能，它提供了与synchronized关键字类似的同步功能，只是<strong>需要使用时显示地获取和释放锁</strong>。虽然它缺少了隐式获取释放锁的便捷性，但是却拥有了<strong>锁获取与释放的可操作性</strong>、<strong>可中断的获取锁</strong>以及<strong>超时获取锁</strong>等多种synchronized锁不具备的同步特征。</p>
<p>简单使用：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">Lock lock&#x3D;new ReentrantLock();
lock.lock();
try&#123;    
&#125;finally&#123;
    lock.unlock();
&#125;
&#x2F;&#x2F;在finally中释放锁，目的是保证在获取到锁之后，最终能够被释放。<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>Lock接口提供synchronized关键字不具备的主要特征：</p>
<p>1.<strong>尝试非阻塞地获取锁</strong>：当前线程尝试获取锁，如果这一时刻锁没有被其他线程获取到，则成功获取并持有锁。</p>
<p>2.<strong>能中断地获取锁</strong>：获取到锁的线程能够响应中断，当获取到锁的线程被中断时，中断异常将会被抛出，同时锁会被释放。</p>
<p>3.<strong>超时获取锁</strong>：在指定时间之前获取到锁，如果截止时间到仍无法获取到锁就返回。</p>
<p><img src="https://gitee.com/modest2001/img/raw/master/yygh/lock%E7%9A%84api.png" alt="lock的api"></p>
<h1 id="队列同步器（AQS）"><a href="#队列同步器（AQS）" class="headerlink" title="队列同步器（AQS）"></a>队列同步器（AQS）</h1><p>队列同步器（AbstractQueuedSynchronizer），是用来构建锁或者其他同步组件的基础框架，它使用了一个<strong>int成员变量表示同步状态</strong>，通过内置的<strong>FIFO队列</strong>来完成资源获取线程的排队工作。</p>
<p>同步器的主要使用方式是<strong>继承</strong>，子类推荐被定义为自定义同步组件的<strong>静态内部类</strong>，同步器自身没有实现任何同步接口，它仅仅是定义了若干同步状态获取和释放的方法来供给自定义同步组件的使用。</p>
<p>同步器和锁的关系：同步器是实现锁的关键，<strong>锁是面向使用者的</strong>，它定义了使用者和锁交互的接口，隐藏了实现细节。<strong>同步器面向的是锁的实现者</strong>，它简化了锁的实现方式<strong>，屏蔽了同步状态管理、线程的排队、等待与唤醒</strong>等底层操作。</p>
<p><img src="https://gitee.com/modest2001/img/raw/master/yygh/%E5%90%8C%E6%AD%A5%E5%99%A8%E6%8E%A5%E5%8F%A3%E6%96%B9%E6%B3%95.png" alt="image-20220416133516559"></p>
<p>同步器提供的模板方法基本上分为三类：独占式获取与释放同步状态、共享式获取与释放同步状态和查询同步队列的等待线程情况。</p>
<p>独占式定义：独占锁就是在<strong>同一个时刻只能有一个线程获取到锁</strong>，而其他获取锁的线程只能处于<strong>同步队列中等待</strong>，只有获取锁的线程释放了锁，后继线程才能获取到锁。</p>
<h2 id="同步队列"><a href="#同步队列" class="headerlink" title="同步队列"></a>同步队列</h2><p>同步器依赖内部的同步队列（FIFO队列）来完成同步状态的管理。核心：<strong>当前线程获取同步状态失败时，同步器会将当前线程以及等待状态等信息构造成为一个节点并将其加入同步队列，同时会阻塞当前线程，当同步状态释放时，会把首节点中的线程唤醒使其再次尝试获取同步状态。</strong></p>
<p>同步队列中的节点：用来保存获取同步状态失败的引用，等待状态以及前驱和后继节点，节点的属性类型与名称。</p>
<p>同步队列节点的属性：</p>
<p><code>volatile int waitStatus;</code></p>
<p><code>volatile Node prev;</code>//前驱节点 </p>
<p><code>volatile Node next;</code>//后继节点 </p>
<p><code>volatile Thread thread;</code>//获取同步状态的线程</p>
<p> <code>Node nextWaiter;</code>//等待队列中的后继节点。 如果节点是共享的的，这个字段将是一个SHARED常量</p>
<p><code>int watiStatus</code></p>
<p>1.CANCELLED，值为1。在同步队列中等待超时或被中断，需要从队列中取消等待，在该状态不会变化。</p>
<p>2.SIGNAL ，值为 -1 。 后继节点地线程处于等待状态，当前节点释放同步状态或者被取消，将会通知后继节点，使后继节点的线程得以运行。</p>
<p>3.CONDITION，值为-2。节点在等待队列中，节点线程等待在Condition上，当其他线程调用了signal()方法，该节点将会从等待队列中转移到同步队列中。</p>
<p>4.PROPAGATE，值为-3。下一次共享式状态获取将会无条件地被传播下去。</p>
<p>5.INITT，值为0。初始状态。</p>
<p><img src="https://gitee.com/modest2001/img/raw/master/yygh/%E5%90%8C%E6%AD%A5%E5%99%A8%E5%92%8C%E9%98%9F%E5%88%97%E7%9A%84%E5%85%B3%E7%B3%BB.png" alt="image-20220416135958618"></p>
<p>当一个线程成功地获取了同步状态（或者锁），其他线程将无法获取到同步状态，转而被构造成为节点并加入到同步队列中，而这个加入队列的过程必须要保证<strong>线程安全</strong>，因此同步器提供了一个基于CAS的设置尾节点的方法：</p>
<p>compareAndSetTail(Node expect,Node update)，它需要传递当前线程“认为”的尾节点和当前节点，只有设置成功后，当前节点才正式与之前的尾节点建立关联。</p>
<p>使用CAS操作判断当前尾节点是否被更改过，如果被更改过就无法设置成功。</p>
<p>设置首节点是通过获取同步状态成功的线程来完成的，由于只有一个线程能够成功获取到同步状态，因此设置头节点的方法不需要CAS操作来保证。</p>
<h2 id="独占式同步状态获取与释放"><a href="#独占式同步状态获取与释放" class="headerlink" title="独占式同步状态获取与释放"></a>独占式同步状态获取与释放</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java">public final void acquire(int arg) &#123;
    if (!tryAcquire(arg) &amp;&amp;
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>上面代码主要完成了<strong>同步状态获取</strong>、<strong>节点构造</strong>、<strong>加入同步队列</strong>以及在<strong>同步队列中自旋</strong>的操作。</p>
<p>1.首先调用自定义同步器实现的tryAcquire(int arg)方法，该方法保证了线程安全的获取同步状态。</p>
<p>2.如果同步状态获取失败，则构造同步节点（Node.EXCLUSIVE，同一时刻只有一个线程成功获取同步状态）。</p>
<p>3.通过addWaiter()方法将节点加入到同步队列的尾部，最后调用acquireQueued方法使得该节点“死循环”的方式获取同步状态。</p>
<p>4.如果获取不到则阻塞节点中的线程，而被阻塞线程唤醒主要依靠前驱节点的出队或者阻塞线程的中断来实现。</p>
<p>addWaiter()方法：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">private Node addWaiter(Node mode) &#123;
	Node node &#x3D; new Node(Thread.currentThread(), mode);
	&#x2F;&#x2F; 快速尝试在尾部添加
	Node pred &#x3D; tail;
	if (pred !&#x3D; null) &#123;
		node.prev &#x3D; pred;
		if (compareAndSetTail(pred, node)) &#123;
				pred.next &#x3D; node;
				return node;
		&#125;
	&#125;
	enq(node);
	return node;
&#125;
private Node enq(final Node node) &#123;
	for (;;) &#123;
		Node t &#x3D; tail;
		if (t &#x3D;&#x3D; null) &#123; &#x2F;&#x2F; Must initialize
			if (compareAndSetHead(new Node()))
					tail &#x3D; head;
		&#125; else &#123;
			node.prev &#x3D; t;
			if (compareAndSetTail(t, node)) &#123;
					t.next &#x3D; node;
					return t;
			&#125;
		&#125;
	&#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>上面addWaiter方法中使用了CAS操作确保了节点能够被线程安全的添加。</p>
<p>在enq方法中，同步器通过“死循环”for(;;)来保证节点的正确添加，在死循环中只有通过CAS操作将节点设置为尾节点之后，当前线程才能从该方法返回，否则当前线程不断地尝试设置。</p>
<p><strong>节点进入同步队列之后，就进入了一个自旋的过程，每一个节点都在自省地观察</strong>，当条件满足，获取到了同步状态，就可以从这个自旋过程中退出，否则依旧留在这个自旋过程中（并且会阻塞当前线程）。</p>
<p><em>核心：头节点是成功获取到同步状态的节点，而头节点的线程释放了同步状态之后，将会唤醒其后续节点、后续节点的线程被唤醒后需要检查自己的前驱节点是否是头节点。</em></p>
<p><img src="https://gitee.com/modest2001/img/raw/master/yygh/%E7%8B%AC%E5%8D%A0%E5%BC%8F%E5%90%8C%E6%AD%A5%E7%8A%B6%E6%80%81%E8%8E%B7%E5%8F%96%E6%B5%81%E7%A8%8B.png" alt="image-20220416142836704"></p>
<p>当前线程执行了相应逻辑后，需要释放同步状态调用同步器relese方法，使后续接地那能够继续获取同步状态。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">&#x2F;&#x2F;relese方法
public final boolean release(int arg) &#123;
	if (tryRelease(arg)) &#123;
		Node h &#x3D; head;
		if (h !&#x3D; null &amp;&amp; h.waitStatus !&#x3D; 0)
				unparkSuccessor(h); &#x2F;&#x2F;该方法使用了LockSupport来唤醒处于等待状态的线程
		return true;
	&#125;
	return false;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p><strong>总结</strong></p>
<p>在获取同步状态时，同步器维护一个同步队列，获取状态失败的线程都将会被加入到同步队列中并在队列中自旋（不断的检查自己前一个节点是不是头节点，获取同步状态），移出队列的条件是前驱节点为头节点且成功获取到了同步状态。在释放同步状态时，同步器调用<code>tryRelease</code>方法释放同步状态，然后唤醒头节点的后继节点。</p>
<h2 id="共享式同步状态获取与释放"><a href="#共享式同步状态获取与释放" class="headerlink" title="共享式同步状态获取与释放"></a>共享式同步状态获取与释放</h2><p>共享式和独占式的主要区别：在于同一时刻能否有多个线程同时获取到同步队列。</p>
<p>在acquireShare方法中，同步器调用tryAcquireShared方法尝试获取同步状态。返回值是int类型的，当返回值大于等于0时，表示能够获取到同步状态。</p>
<p>如果当前节点的前驱是否为头节点，尝试获取同步状态，如果返回值大于等于0，表示该次获取同步状态成功并从自旋过程中退出。共享式也需要释放同步状态，但是调用的是releaseShare方法。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">public final boolean releaseShared(int arg) &#123;
	if (tryReleaseShared(arg)) &#123;
		doReleaseShared();
		return true;
	&#125;
	return false;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>该方法在释放同步状态之后，将会唤醒后续处于等待状态的节点。对于能够支持多个线程同时访问的并发组件（比如Semaphore），它和独占式主要区别在于tryReleaseShared(int arg)方法<strong>必须确保同步状态（或者资源数）线程安全释放</strong>，一般是<strong>通过循环和CAS操作来保证</strong>的，因为释放同步状态的操作会同时来自多个线程。</p>
<h2 id="独占式超时获取同步状态"><a href="#独占式超时获取同步状态" class="headerlink" title="独占式超时获取同步状态"></a>独占式超时获取同步状态</h2><p>通过调用同步器doAcquireNanos（）方法可以超时获取同步状态，即在指定时间段内获取同步状态，如果获取到同步状态则返回true，否则返回false。</p>
<p>响应中断的同步状态获取过程：当一个线程获取不到锁而被阻塞在synchronized之外，对该线程进行中断操作，此时线程的中断标志位会被修改，但线程依旧会被阻塞在synchronized上，等待着获取锁。在java 5后同步器提供acquireInterruptibly方法，这个方法再等待获取同步状态，如果当前线程被中断会立刻返回并抛出异常。</p>
<p> 如果当前线程获取同步状态失败，则判断是否超时（nanosTimeout小于等于0表示已经超时），如果没有超时，重新计算超时间隔nanosTimeout，然后使当前线程等待nanosTimeout纳秒（当已到设置的超时时间，该线程会从LockSupport.parkNanos(Objectblocker,long nanos)方法返回）。<br> 如果nanosTimeout小于等于spinForTimeoutThreshold（1000纳秒）时，将不会使该线程进行超时等待，而是进入快速的自旋过程</p>
<p><img src="https://gitee.com/modest2001/img/raw/master/yygh/%E7%8B%AC%E5%8D%A0%E5%BC%8F%E8%B6%85%E6%97%B6%E8%8E%B7%E5%8F%96%E5%90%8C%E6%AD%A5%E7%8A%B6%E6%80%81.png" alt="image-20220416152553750"></p>
<h1 id="重入锁"><a href="#重入锁" class="headerlink" title="重入锁"></a>重入锁</h1><p><em>定义：重入锁，就是支持重进入的锁，它表示该锁能够支持一个线程对资源的重复加锁。其中还支持获取锁时的公平和非公平的选择。</em></p>
<p>synchronized关键字隐式的支持重进入，ReentrantLock虽然不是支持隐式的重进入，但是在调用lock()方法时，已经获取到锁的线程能够再次调用lock方法而不被阻塞。</p>
<p>锁的获取情况：公平获取，非公平获取（默认）。公平：先申请的先获取锁，反之就是非公平的。（非公平锁的效率，肯定是优于公平锁的）</p>
<h2 id="重进入"><a href="#重进入" class="headerlink" title="重进入"></a>重进入</h2><p><em>重进入是指任意线程在获取到锁之后能够再次获取该锁而不会被锁所阻塞。</em></p>
<p>重进入的两个问题：</p>
<p>1.<strong>线程再次获取锁</strong>。锁需要去是被获取锁的线程是否为当前占据锁的线程，如果是就再次释放。</p>
<p>2.<strong>锁的最终释放</strong>。线程重复了n次获取锁，随后在第n次后释放该锁，其他线程能够获取到该锁。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">final boolean nonfairTryAcquire(int acquires) &#123;
    final Thread current &#x3D; Thread.currentThread();
    int c &#x3D; getState();
    if (c &#x3D;&#x3D; 0) &#123;
        if (compareAndSetState(0, acquires)) &#123;
            setExclusiveOwnerThread(current);
            return true;
        &#125;
    &#125;
    else if (current &#x3D;&#x3D; getExclusiveOwnerThread()) &#123;
        int nextc &#x3D; c + acquires;  &#x2F;&#x2F;增加同步状态
        if (nextc &lt; 0) &#x2F;&#x2F; overflow
            throw new Error(&quot;Maximum lock count exceeded&quot;);
        setState(nextc);
        return true;
    &#125;
    return false;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>此方法通过判断 当前线程是否为获取锁的线程 来决定获取操作是否成功，如果是获取锁的线程再次请求，则将同步状态值进行增加并返回true，表示获取同步状态成功。</p>
<h2 id="公平锁和非公平锁"><a href="#公平锁和非公平锁" class="headerlink" title="公平锁和非公平锁"></a>公平锁和非公平锁</h2><p>公平性与否是针对获取锁而言的，如果一个锁是公平的，那么锁的获取顺序就应该符合请求的绝对时间顺序，也就是 FIFO。</p>
<p>对于非公平锁，只要CAS设置同步状态成功，则表示当前线程获取了锁。</p>
<p>对于公平节锁，只要判断当前节点是不是首节点来判断是否能够获取到锁。</p>
<p>性能总结：公平性锁保证了锁的获取安装FIFO原则，而代价是进行大量的线程切换，非公平锁虽然可能造成线程“饥饿”，但极少的线程切换，保证了其更大的吞吐量。</p>
<h1 id="读写锁"><a href="#读写锁" class="headerlink" title="读写锁"></a>读写锁</h1><p><em>读写锁：读写锁维护了一对锁，一个读锁和一个写锁，通过分离读锁和写锁，使得并发性相比一般的排它锁性能更好。</em></p>
<p><em>排他锁：在同一时刻只允许一个线程进行访问。</em></p>
<p>读写锁和排它锁的区别：读写锁在同一时刻可以允许多个线程访问，但是在写线程访问时，所有的读线程和其他写线程都将会被阻塞。</p>
<p>使用写锁被获取到时，后续（非当前写操作线程）的读写操作都会被阻塞，写锁释放之后，所有操作才能继续执行。（保证了不会出现脏读）</p>
<p>ReentrantReadWriteLock特性：</p>
<ul>
<li>公平性选择 ：支持公平和非公平的方式获取锁，吞吐量非公平优于公平。</li>
<li>重进入 ： 读锁在获取锁之后再获取读锁，写锁在获取锁之后再获取读锁和写锁。</li>
<li>锁降级 ：遵循获取写锁、获取读锁在释放写锁的次序，写锁能够降级为读锁。</li>
</ul>
<p>读写锁的接口与示例 ReadWriteLock仅定义了获取读锁和写锁的两个方法，即readLock()方法和writeLock()方法，而其实现类ReentrantReadWriteLock，除了接口方法之外，还提供了一些便于外界监控其内部工作状态的方法，这些方法如下：</p>
<ul>
<li>getReadLockCount()：返回当前读锁获取的次数</li>
<li>getReadHoldCount()：返回当前线程获取读锁的次数</li>
<li>isWriteLocked()：判断写锁是否被获取</li>
<li>getWriteHoldCount()：返回当前写锁被获取的次数</li>
</ul>
<p>通过读写锁保证hashmap读写线程安全实例：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">static Map&lt;String, Object&gt; map &#x3D; new HashMap&lt;&gt;();
static ReentrantReadWriteLock rwl &#x3D; new ReentrantReadWriteLock();
static Lock r &#x3D; rwl.readLock();
static Lock w &#x3D; rwl.writeLock();
&#x2F;**
 * 获取一个key对应的value
 *&#x2F;
public static final Object get(String key) &#123;
    r.lock();
    try &#123;
        return map.get(key);
    &#125; finally &#123;
        r.unlock();
    &#125;
&#125;
&#x2F;**
 * 设置key对应的value，并返回旧的value
 *&#x2F;
public static final Object put(String key, Object value) &#123;
    w.lock();
    try &#123;
        return map.put(key, value);
    &#125; finally &#123;
        w.unlock();
    &#125;
&#125;
&#x2F;**
 * 清空所有的内容
 *&#x2F;
public static final void clear() &#123;
    w.lock();
    try &#123;
        map.clear();
    &#125; finally &#123;
        w.unlock();
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>Cache组合一个非线程安全的hashmap作为缓存的实现，同时使用了读写锁的读锁和写锁来保证Cache是线程安全的。</p>
<p>核心步骤：</p>
<p>1.在读操作get()方法中，需要获取读锁，这使得并发访问该方法不会被阻塞。</p>
<p>2.写操作put,clear等方法，在更新hashmap时必须要获取到写锁，当获取到写锁时，其他线程的读锁和写锁均会被阻塞（自己线程的不会被阻塞）。</p>
<p>3.只有当写锁释放后，其他线程的读写操作才能继续执行。</p>
<h2 id="读写状态的设计"><a href="#读写状态的设计" class="headerlink" title="读写状态的设计"></a>读写状态的设计</h2><p>读写状态也需要自定义同步器来实现同步功能，而读写状态就是其同步器的同步状态。在重入锁（ReentrantLock）中同步状态表示为锁被一个线程重复获取的次数。而读写锁的自定义同步器需要在同步状态上维护多个读线程和一个写线程的状态。</p>
<p>因为同步状态是int类型，是32位bit所以我设置为高16位为读状态，低16位为写状态。如下：</p>
<p><img src="https://gitee.com/modest2001/img/raw/master/yygh/%E8%AF%BB%E5%86%99%E7%8A%B6%E6%80%81%E8%AE%BE%E8%AE%A1.png" alt="image-20220416161108540"></p>
<p><em>结论：S不等于0时，当写状态（S&amp;0x0000FFFF）等于0时，则读状态（S&gt;&gt;&gt;16）大于0，即读锁已被获取。</em></p>
<h2 id="读写锁的获取和释放"><a href="#读写锁的获取和释放" class="headerlink" title="读写锁的获取和释放"></a>读写锁的获取和释放</h2><p><strong>写锁的获取和释放</strong></p>
<p><em>写锁是一个直冲<strong>重进入</strong>的<strong>排他锁</strong>。</em></p>
<p>核心：如果<strong>当前线程已经获取到写锁，则增加写状态</strong>。如果当前线程在获取写锁时，读锁已经被获取或者该线程不是已经获取写锁的线程，则当前线程进入等待状态。</p>
<p><strong>如果存在读锁，则写锁不能被获取</strong>。因为：读写锁需要确保写操作对读锁可见。因此，只有等待其他读线程都释放了读锁，写锁才能被当前线程获取，而写锁一旦被获取，则其他读写线程的后续访问均被阻塞。</p>
<p>释放过程：<strong>每次释放均减少写状态，当写状态为0时表示写锁已被释放</strong>，从而等待的读写线程能够继续访问读写锁，同时前次写线程的修改对后续写线程可见。</p>
<p><strong>读锁的获取和释放</strong></p>
<p><em>读锁是一个支持<strong>重进入</strong>的<strong>共享锁</strong>。</em></p>
<p>它能够被多个线程同时获取，在没有写锁的情况下，读锁总是能够被成功的获取，而<strong>只需要线程安全的增加读状态</strong>。</p>
<p>核心：<strong>如果当前线程线程已经获取了读锁，则增加读状态</strong>。如果当期线程在获取读锁时，写锁已经别其他线程获取到了，那么就会处于等待状态。</p>
<p><strong>读状态是所有线程获取读锁次数的总和</strong>，而每个线程各自获取读锁的次数只能选择保存在ThreadLocal中。</p>
<p>释放过程：读锁的每次释放均减少读状态，减少值是(1&lt;&lt;16)。</p>
<h2 id="锁降级"><a href="#锁降级" class="headerlink" title="锁降级"></a>锁降级</h2><p>锁降级是指的写锁降级成为读锁。锁降级是指把持住（当前拥有的）写锁，再获取读锁，随后释放（先前拥有的）写锁的过程。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">&#x2F;&#x2F;当数据发生变更后，update变量（布尔类型且volatile修饰）被设置为false
public void processData() &#123;
    readLock.lock();
    if (!update) &#123;
        &#x2F;&#x2F; 必须先释放读锁
        readLock.unlock();
        &#x2F;&#x2F; 锁降级从写锁获取到开始
        writeLock.lock();
        try &#123;
            if (!update) &#123;
                &#x2F;&#x2F; 准备数据的流程（略）
                update &#x3D; true;
            &#125;
            readLock.lock();
        &#125; finally &#123;
            writeLock.unlock();
        &#125;
        &#x2F;&#x2F; 锁降级完成，写锁降级为读锁
    &#125;
    try &#123;
        &#x2F;&#x2F; 使用数据的流程（略）
    &#125; finally &#123;
        readLock.unlock();
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>上述示例中，当数据发生变更后，布尔类型且<strong>volatile修饰update变量</strong>被设置为false，此时所有访问processData()方法的线程都能够感知到变化，但只有一个线程能够获取到写锁，其他线程会被阻塞在读锁和写锁的lock()方法上。当前线程获取写锁完成数据准备之后，再获取读锁，随后释放写锁，完成锁降级。</p>
<p>这样锁降级读锁的目的：主要是为了保证数据的可见性，如果当前线程不获取读锁而是直接释放写锁，假设此时另一个线程T获取了写锁并修改了数据，那么当前线程无法感知线程T的数据更新。如果当前线程获取了读锁，即遵循锁降级的步骤，则线程T将会被阻塞，知道当前线程使用数据并释放读锁之后，线程才能获取写锁并进行数据更新。</p>
<h1 id="LockSupport工具"><a href="#LockSupport工具" class="headerlink" title="LockSupport工具"></a>LockSupport工具</h1><p>当需要阻塞或唤醒一个线程的时候，都会使用LockSupport工具类进行完成，LockSupport定义了一组公共的静态方法，这方法提供了基本的线程阻塞和唤醒功能。AQS框架借助于两个类：Unsafe(提供CAS操作) 和 LockSupport(提供park/unpark操作)。因此，LockSupport可谓构建concurrent包的基础之一。</p>
<p><img src="https://gitee.com/modest2001/img/raw/master/yygh/LockSupport.png" alt="image-20220416172611561"></p>
<h1 id="Condition接口"><a href="#Condition接口" class="headerlink" title="Condition接口"></a>Condition接口</h1><p>任意一个java对象，都拥有一组监视器方法。</p>
<p>Object自带的方法和synchronized关键字，实现等待/通知模式。</p>
<p>Condition接口也提供了类似的Object的监视器方法，与lock配合实现等待/通知模式。</p>
<p>condition对象是由lock对象创建出来的，所以condition依赖lock对象前提是需要获取到锁。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">void await():
当前线程从运行状态进入等待状态或者中断，直到被通知唤醒。
boolean await(long time, TimeUnit unit)；
当前线程进入等待状态，直到被通知、中断或者超时
boolean awaitUntil(Date deadline)
当前线程进入等待状态，直到被通知、中断或者到达指定的时间。到达指定的时间返回
false，否则返回true（还没有导致指定时间就被唤醒）
void signal():
唤醒一个等待在Condition上的线程，但是必须获得与该Condition相关的锁
void signalAll():
唤醒所有等待在Condition上的线程，但是必须获得与该Condition相关的锁<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h2 id="Condition实现分析"><a href="#Condition实现分析" class="headerlink" title="Condition实现分析"></a>Condition实现分析</h2><p>Condition是同步器AQS的内部类，每个Condition对象都包含一个队列（等待队列）。</p>
<p><strong>等待队列</strong></p>
<p>等待队列是一个FIFO队列，在队列中的每个节点都包含了一个线程引用，该线程就是在Condition对象上等待的线程，如果一个线程调用了Condition.await()方法，那么该线程将会释放锁、构成节点加入等待队列并进入等待状态。</p>
<p>当线程调用await方法的时候，将节点从尾部加入到等待队列中。此过程不需要CAS保证，因为调用这个方法的前提是已经获取到了锁，所以整个过程都是锁在保证线程安全。</p>
<p>Object一个对象拥有一个队列和等待队列，而并发包（同步器）中拥有一个队列和多个等待队列。</p>
<p><img src="https://gitee.com/modest2001/img/raw/master/yygh/%E5%B9%B6%E5%8F%91%E5%8C%85%E4%B8%AD%E5%90%8C%E6%AD%A5%E9%98%9F%E5%88%97%E5%92%8C%E7%AD%89%E5%BE%85%E9%98%9F%E5%88%97.png" alt="image-20220416175214389"></p>
<p>因此每个Condition实例都能够访问同步器提供的方法，相当于每个Condition都拥有所属同步器的引用。</p>
<p><strong>等待</strong></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">public final void await() throws InterruptedException &#123;
    if (Thread.interrupted())
        throw new InterruptedException();
    &#x2F;&#x2F; 通过addConditionWaiter()方法把当前线程构造成一个新的节点并将其加入等待队列中
    Node node &#x3D; addConditionWaiter();
    &#x2F;&#x2F; 释放同步状态，也就是释放锁
    int savedState &#x3D; fullyRelease(node);
    int interruptMode &#x3D; 0;
    &#x2F;&#x2F;判断节点是否在同步队列
    while (!isOnSyncQueue(node)) &#123;
        &#x2F;&#x2F;在等待队列，进入等待
        LockSupport.park(this); &#x2F;&#x2F;调用的LockSupport进行阻塞
        if ((interruptMode &#x3D; checkInterruptWhileWaiting(node)) !&#x3D; 0)
            break;
    &#125;
    &#x2F;&#x2F;调用同步器的acquireQueued()方法加入到获取同步状态的竞争中
    if (acquireQueued(node, savedState) &amp;&amp; interruptMode !&#x3D; THROW_IE)
        interruptMode &#x3D; REINTERRUPT;
    if (node.nextWaiter !&#x3D; null)
        unlinkCancelledWaiters();
    if (interruptMode !&#x3D; 0)
        reportInterruptAfterWait(interruptMode);
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>从上面可以看出调用了LockSupport进行了阻塞，但是在这之前先释放了锁。</p>
<p>调用该方法的线程成功获取了锁的线程，也就是同步队列的首节点，该方法会将当前线程构造成节点并加入等待队列中，然后释放同步状态，唤醒同步队列中的后继节点，然后当前线程进入等待状态。</p>
<p><strong>通知</strong></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">public final void signal() &#123;
    &#x2F;&#x2F;检查调用signal的线程是否是锁的持有者
    if (!isHeldExclusively())
        throw new IllegalMonitorStateException();
    &#x2F;&#x2F;获取等待队列的首节点
    Node first &#x3D; firstWaiter;
    if (first !&#x3D; null)
        doSignal(first);
&#125;

private void doSignal(Node first) &#123;
    do &#123;
        if ( (firstWaiter &#x3D; first.nextWaiter) &#x3D;&#x3D; null)
            lastWaiter &#x3D; null;
        first.nextWaiter &#x3D; null;
    &#125; while (!transferForSignal(first) &amp;&amp;
             (first &#x3D; firstWaiter) !&#x3D; null);
&#125;

final boolean transferForSignal(Node node) &#123;
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;
		&#x2F;&#x2F;通过调用同步器的enq(Node node)方法，等待队列中的头节点线程安全地移动到同步队列
        Node p &#x3D; enq(node);
        int ws &#x3D; p.waitStatus;
  	    &#x2F;&#x2F;当节点移动到同步队列后，当前线程再使用LockSupport唤醒该节点的线程
        if (ws &gt; 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            LockSupport.unpark(node.thread);
        return true;
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>由源码知道调用了同步器的enq方法，带带队列的头节点线程安全移动到同步对队列中。</p>
<p>当节点移动到同步队列后，当前线程再使用了LockSupport唤醒该节点的线程。</p>
<p>唤醒的线程，将从await方法中的循环中退出，进而调用同步器acquireQueue方法加入到获取同步状态的竞争中。</p>
<p>成功获取同步状态之后，被唤醒的线程从先前调用的await方法返回，此时线程已经成功获取到了锁。</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/dai_modest/about" rel="external nofollow noreferrer">戴某人</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://modest2001.gitee.io/dai_modest/dai_modest/2022/04/16/java-bing-fa-bian-cheng-de-yi-zhu-di-wu-zhang-zong-jie/">https://modest2001.gitee.io/dai_modest/dai_modest/2022/04/16/java-bing-fa-bian-cheng-de-yi-zhu-di-wu-zhang-zong-jie/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/dai_modest/about" target="_blank">戴某人</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/dai_modest/tags/java/">
                                    <span class="chip bg-color">java</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/dai_modest/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/dai_modest/libs/share/js/social-share.min.js"></script>
    

    
    <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid="></script>
    <div class="addthis_inline_share_toolbox"></div>
    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/dai_modest/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/dai_modest/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/dai_modest/2022/05/25/sou-suo-he-hui-su-lian-xi-1/">
                    <div class="card-image">
                        
                        
                        <img src="/dai_modest/medias/featureimages/5.jpg" class="responsive-img" alt="搜索和回溯练习1">
                        
                        <span class="card-title">搜索和回溯练习1</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            回溯练习，每10题一个合集
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-05-25
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/dai_modest/categories/%E7%AE%97%E6%B3%95/" class="post-category">
                                    算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/dai_modest/tags/java/">
                        <span class="chip bg-color">java</span>
                    </a>
                    
                    <a href="/dai_modest/tags/%E6%90%9C%E7%B4%A2%EF%BC%8C%E5%9B%9E%E6%BA%AF/">
                        <span class="chip bg-color">搜索，回溯</span>
                    </a>
                    
                    <a href="/dai_modest/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/dai_modest/2022/04/16/java-bing-fa-bian-cheng-de-yi-zhu-di-liu-zhang-zong-jie-1/">
                    <div class="card-image">
                        
                        
                        <img src="/dai_modest/medias/featureimages/8.jpg" class="responsive-img" alt="《java并发编程的艺术》第六章总结1">
                        
                        <span class="card-title">《java并发编程的艺术》第六章总结1</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            ConcurrentHashMap的结构（JDK1.7和JDK1.8）
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-04-16
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/dai_modest/categories/%E4%B9%A6%E7%B1%8D/" class="post-category">
                                    书籍
                                </a>
                            
                            <a href="/dai_modest/categories/%E4%B9%A6%E7%B1%8D/%E7%AC%94%E8%AE%B0%E7%B1%BB/" class="post-category">
                                    笔记类
                                </a>
                            
                            <a href="/dai_modest/categories/%E4%B9%A6%E7%B1%8D/%E7%AC%94%E8%AE%B0%E7%B1%BB/%E3%80%8Ajava%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E7%9A%84%E8%89%BA%E6%9C%AF%E3%80%8B/" class="post-category">
                                    《java并发编程的艺术》
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/dai_modest/tags/java/">
                        <span class="chip bg-color">java</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE' || selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 戴某的博客<br />'
            + '文章作者: 戴某人<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者：戴某人所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/dai_modest/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/dai_modest/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/dai_modest/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/dai_modest/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/dai_modest/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/dai_modest/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/dai_modest/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2023</span>
            
            <span id="year">2019</span>
            <a href="/dai_modest/about" target="_blank">戴某人</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">128.1k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">


    <a href="mailto:861796830@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=861796830" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 861796830" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/dai_modest/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/dai_modest/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/dai_modest/libs/materialize/materialize.min.js"></script>
    <script src="/dai_modest/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/dai_modest/libs/aos/aos.js"></script>
    <script src="/dai_modest/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/dai_modest/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/dai_modest/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/dai_modest/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/dai_modest/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
        <div style="position:fixed;bottom:125px;right:16px;cursor: pointer;">
            <a title="兔小巢" target="_blank" rel="noopener" href="https://support.qq.com/products/"><i class="fa fa-comments fa-3x"  aria-hidden="true"></i></a>
        </div>
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/dai_modest/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/dai_modest/libs/background/ribbon.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/dai_modest/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/dai_modest/libs/instantpage/instantpage.js" type="module"></script>
    

<script src="/dai_modest/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>

</html>
